#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QSettings>
#include "ClassCollector.h"
#include "ui_ClassCollector.h"
#include "Include/Settings.h"

ClassCollector::ClassCollector(QWidget *parent):
    QDialog(parent),
    ui(new Ui::ClassCollector)
{
    ui->setupUi(this);

    _proc = new QProcess(this);
    connect(_proc, SIGNAL(readyRead()), SLOT(onReadyRead()));
    connect(_proc, SIGNAL(finished(int)), SLOT(onRunFinished(int)));
    connect(_proc, SIGNAL(error(QProcess::ProcessError)), SLOT(onRunError(QProcess::ProcessError)));
    _proc->setWorkingDirectory(QDir::currentPath() + QDir::separator() + "python3");

    ui->progressBar->setValue(0);
}

ClassCollector::~ClassCollector()
{
    delete ui;
}

void ClassCollector::showEvent(QShowEvent *)
{
    QSettings set;
    _proc->start(Plugins::Settings::instance()->py3(), QStringList() << "-u" << "ClassCollector.py" << QFileInfo(set.fileName()).absoluteDir().path());
}

void ClassCollector::closeEvent(QCloseEvent *)
{
    if (_proc->state() == QProcess::Running)
        _proc->terminate();
}

void ClassCollector::onReadyRead()
{
    _proc->setReadChannel(QProcess::StandardOutput);
    QByteArray text;
    while(!(text = _proc->readLine()).isEmpty()){
        if (text.startsWith("len:")){
            int len = text.trimmed().mid(4).toInt();
            ui->progressBar->setMaximum(len);
        } else if (text.startsWith("count:")){
            int count = text.trimmed().mid(6).toInt();
            ui->progressBar->setValue(count);
        }
    }
}

void ClassCollector::onRunFinished(int)
{
    accept();
}

void ClassCollector::onRunError(QProcess::ProcessError err)
{
    switch(err){
    case QProcess::FailedToStart:
        QMessageBox::critical(this, tr("Collect"), tr("The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program."), "error bold");
        break;
    case QProcess::Crashed:
        QMessageBox::critical(this, tr("Collect"), tr("The process crashed some time after starting successfully."), "error bold");
        break;
    case QProcess::WriteError:
        QMessageBox::critical(this, tr("Collect"), tr("An error occurred when attempting to write to the process. For example, the process may not be running, or it may have closed its input channel."), "error bold");
        break;
    case QProcess::ReadError:
        QMessageBox::critical(this, tr("Collect"), tr("An error occurred when attempting to read from the process. For example, the process may not be running."), "error bold");
        break;
    default:
        QMessageBox::critical(this, tr("Collect"), tr("An error occurred when attempting to read from the process. For example, the process may not be running."), "error bold");
        break;
    }
}
